package com.enterprise.support.servlet;

import com.enterprise.support.utility.Configuration;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.servlet.KaptchaServlet;
import com.google.code.kaptcha.util.Config;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Zhanggaojiang
 * Date: 11-1-19
 * Time: 上午10:20
 * Email: z82422@gmail.com
 * 漂亮的 图形验证码
 */

public class CaptchaServlet extends KaptchaServlet {
    public static String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    private Properties props;
    private Producer kaptchaProducer;
    private String sessionKeyValue;

    public CaptchaServlet() {
        props = Configuration.getProperties("/config/verifycptcha.properties");
        kaptchaProducer = null;
        sessionKeyValue = null;
    }

    public void init(ServletConfig conf) throws ServletException {
        super.init(conf);
        ImageIO.setUseCache(false);
        Config config = new Config(props);
        kaptchaProducer = config.getProducerImpl();
        sessionKeyValue = config.getSessionKey();
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletOutputStream out = resp.getOutputStream();
        resp.setDateHeader("Expires", 0L);
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        resp.setHeader("Pragma", "no-cache");
        resp.setContentType("image/jpeg");
        String capText = kaptchaProducer.createText();
        req.getSession().setAttribute(sessionKeyValue, capText);
        BufferedImage bi = kaptchaProducer.createImage(capText);
        ImageIO.write(bi, "jpeg", out);
        out.close();
    }

}